import os
import cv2
import numpy as np
import subprocess

def find_specific_video_devices():
    """
    查找特定的视频设备 (Linux上使用v4l2-ctl)。
    在非Linux系统上，此函数可能需要调整或使用其他方法。
    返回一个字典，键是自定义的相机名 (如 'cap_main', 'cap_aux')，值是设备路径 (如 '/dev/video0')。
    """
    valid_devices = {}
    try:
        # 尝试执行 v4l2-ctl 命令
        process = subprocess.Popen(['v4l2-ctl', '--list-devices'],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        stdout, stderr = process.communicate(timeout=5) # 添加超时
        devices_output = stdout.decode('utf-8').strip()

        if process.returncode != 0 or not devices_output:
            print(f"警告: 'v4l2-ctl --list-devices' 执行失败或无输出。Stderr: {stderr.decode('utf-8').strip()}")
            # 在这里可以尝试备用方法，或者直接返回空
            #如果v4l2-ctl失败，我们尝试使用默认的0和1作为备选
            if not valid_devices: # 只有当v4l2-ctl完全没找到时
                print("尝试使用默认索引 0 和 1 作为备选相机。")
                if cv2.VideoCapture(0).isOpened(): valid_devices['cap_generic_0_fallback'] = 0
                if cv2.VideoCapture(1).isOpened(): valid_devices['cap_generic_1_fallback'] = 1
            return valid_devices

        devices_blocks = devices_output.split('\n\n')

        for device_block in devices_blocks:
            if not device_block.strip():
                continue
            lines = device_block.strip().split('\n')
            if len(lines) < 2:
                print(f"警告: 格式错误的设备块: {device_block}")
                continue

            device_name_line = lines[0].strip()
            # 通常设备路径在第二行，并且是该行的第一个词条
            # 例如： /dev/video0
            # 有时可能是：      /dev/video0 (前面有空格)
            device_path = ""
            for line_part in lines:
                if line_part.strip().startswith('/dev/video'):
                    device_path = line_part.strip().split()[0] # 取第一个，以防后面有其他信息
                    break
            
            if not device_path:
                print(f"警告: 未能在块中找到 /dev/video 路径: {device_block}")
                continue

            # 根据设备名称分配键名
            # 注意：这些名称是示例，你需要根据你的摄像头实际名称调整
            if "DF100-720P" in device_name_line or "DECXIN" in device_name_line:
                valid_devices['cap_main'] = device_path
            elif "HD USB Camera" in device_name_line : 
                valid_devices['cap_aux'] = device_path
            elif "Integrated Camera" in device_name_line: # 示例：笔记本内置摄像头
                 if 'cap_main' not in valid_devices: # 优先给主摄像头
                    valid_devices['cap_main'] = device_path
                 elif 'cap_aux' not in valid_devices:
                    valid_devices['cap_aux'] = device_path
            else: # 如果找不到特定相机，则使用通用相机名
                if 'cap_generic_0' not in valid_devices and device_path not in valid_devices.values():
                    valid_devices['cap_generic_0'] = device_path
                elif 'cap_generic_1' not in valid_devices and device_path not in valid_devices.values():
                    valid_devices['cap_generic_1'] = device_path
                # 可以继续添加 cap_generic_2 等

    except FileNotFoundError:
        print("错误: 未找到 v4l2-ctl 命令。请确保已安装 (通常用于Linux)。")
        # 备用逻辑 (同上)
        if not valid_devices:
            print("尝试使用默认索引 0 和 1 作为备选相机。")
            if cv2.VideoCapture(0).isOpened(): valid_devices['cap_generic_0_fallback'] = 0
            if cv2.VideoCapture(1).isOpened(): valid_devices['cap_generic_1_fallback'] = 1
    except subprocess.TimeoutExpired:
        print("错误: 'v4l2-ctl --list-devices' 命令执行超时。")
    except subprocess.CalledProcessError as e:
        print(f"执行 v4l2-ctl 时出错: {e}")
    except Exception as e:
        print(f"在 find_specific_video_devices 中发生意外错误: {e}")

    print(f"找到的视频设备: {valid_devices}")
    return valid_devices

